package com.googlecode.connectlet.machine.provider.key;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactorySpi;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

public final class MachinePrivateKeyFactory extends KeyFactorySpi {
	@Override
	protected PrivateKey engineGeneratePrivate(KeySpec
			keySpec) throws InvalidKeySpecException {
		if (keySpec instanceof MachinePrivateKeySpec) {
			return ((MachinePrivateKeySpec) keySpec).getPrivateKey();
		}
		throw new InvalidKeySpecException("MachinePrivateKeySpec required");
	}

	@Deprecated
	@Override
	protected PublicKey engineGeneratePublic(KeySpec keySpec) {
		throw new UnsupportedOperationException();
	}

	@Override
	protected <T extends KeySpec> T engineGetKeySpec(Key key,
			Class<T> keySpec) throws InvalidKeySpecException {
		if (keySpec.isAssignableFrom(MachinePrivateKeySpec.class)) {
			if (key instanceof MachinePrivateKey) {
				MachinePrivateKey newKey = (MachinePrivateKey) key;
				return keySpec.cast(new MachinePrivateKeySpec(newKey).getEncoded());
			}
			throw new InvalidKeySpecException("MachinePrivateKey required");
		}
		throw new InvalidKeySpecException("keySpec must be MachinePrivateKeySpec");
	}

	@Override
	protected Key engineTranslateKey(Key key) throws InvalidKeyException {
		if (key instanceof MachinePrivateKey) {
			return key;
		}
		throw new InvalidKeyException("MachinePrivateKey required");
	}
}